package com.baic.ibase.utils.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

public class TokenUtils {

    private static final String TOKEN_KEY = "ibae_device_secret_key";


    private static final Long TOKEN_EXPIRE_TIME = 8640000L;

    public static String createToken(String userId, String userName) {

        return JWT.create()
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME))
                .sign(Algorithm.HMAC256(TOKEN_KEY));

    }

    public static String getUserId(String token) {

        return JWT.decode(token).getClaim("userId").asString();

    }

    public static String getUserName(String token) {

        return JWT.decode(token).getClaim("userName").asString();

    }

    public static boolean verify(String token) {

        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_KEY)).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }

    }


}
